package com.zy.web.demo.duoxiancheng.demo28;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author <a href="mailto:zhouyong@cqyyt.com">zy</a>
 * @version 1.0
 * @date 2020/8/28 14:40
 * 生产者消费者
 */
public class Shenchan28 {

    public static final int INT = 10;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private int zy = 10;

    public void shenchan(){
        lock.lock();
        try {
            while ( zy == INT ){
                System.out.println("物品数量："+zy+"；生产停止");
                condition.await();
            }
            zy++;
            System.out.println("生产物品的数量："+zy);
            condition.signalAll();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void xiaofei(){
        lock.lock();
        try {
            while ( zy == 0 ){
                System.out.println("物品数量："+zy+"；消费停止");
                condition.await();
            }
            zy--;
            System.out.println("消费物品的数量："+zy);
            condition.signalAll();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}
